package com.example.classload;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author xia
 * @className MyClassLoadTest
 * @date 2022/9/30 16:46
 */
public class MyClassLoadTest extends ClassLoader{

    private String classPath;

    public MyClassLoadTest(String classPath) {
        this.classPath = classPath;
    }

    private byte[] loadByte(String name) throws IOException {
        name = name.replace("\\.", "/");
        FileInputStream inputStream = new FileInputStream(classPath + "/" + name + ".class");
        int available = inputStream.available();

        byte[] bytes = new byte[available];
        inputStream.read(bytes);
        inputStream.close();

        return bytes;
    }

    @Override
    protected Class<?> findClass(String name){
        try {
            byte[] bytes = loadByte(name);

            return defineClass(name, bytes, 0, bytes.length);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
